package Linklist;

import java.util.HashSet;
import java.util.Set;

/**
 * @Classname JZ52两个链表的第一个公共节点
 * @Description TODO
 * @Date 2023/2/11 13:39
 * @Created by xjl
 */
public class JZ52两个链表的第一个公共节点 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    // 采用的是双指针的方式
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

    ListNode getIntersectionNodecpoy(ListNode headA, ListNode headB) {
        if (headA==null|| headB==null){
            return null;
        }
        ListNode pA=headA;
        ListNode pB=headB;
        while (pA!=pB){
            pA=pA==null?headB:pA.next;
            pB=pB==null?headA:pB.next;
        }
        return pA;
    }

    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
}
